import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getAccessToken, getRefreshToken, removeToken, setAccessToken, setRefreshToken } from "@/utils/cache/cookies"
import { resetRouter } from "@/router"
import { loginApi, getUserInfoApi, refreshTokenApi } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"
import routeSettings from "@/config/route"

export const useUserStore = defineStore("user", () => {
  const accessToken = ref<string>(getAccessToken() || "")
  const refreshToken = ref<string>(getRefreshToken() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const avatar = ref<string>("")
  const userDetail = ref()

  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 登录 */
  const login = async ({ username, password, code }: LoginRequestData) => {
    const { data } = await loginApi({ username, password, code })
    accessToken.value = setAccessToken(data.access_token)
    refreshToken.value = setRefreshToken(data.refresh_token)
  }
  /** 获取用户信息 */
  const getInfo = async () => {
    const { data } = await getUserInfoApi()
    // 给userDetail赋值
    userDetail.value = data
    console.log("@@@", data)
    username.value = data.username
    avatar.value = data.avatar
    // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
  }
  // /** 获取用户详情 */
  // const getUserDetail = () => {}
  /** 模拟角色变化 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    accessToken.value = setAccessToken(newToken)
    // accessToken.value = newToken
    // setAccessToken(newToken)
    // 用刷新页面代替重新登录
    window.location.reload()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    accessToken.value = ""
    refreshToken.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    accessToken.value = ""
    refreshToken.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }
  const _refreshToken = async () => {
    const resp = await refreshTokenApi()
    console.log("刷新返回", resp)
    if (resp.code === 200) {
      setAccessToken(resp.data.access_token)
      console.log("token刷新成功")
      return "刷新成功"
    } else {
      console.log("刷新失败")
      return Promise.reject(new Error("刷新失败"))
    }
  }
  // const updateQuserStatus = async (status:boolean) => {
  //   await updateBindStatus(status)
  // }

  return {
    accessToken,
    refreshToken,
    roles,
    username,
    avatar,
    userDetail,
    login,
    getInfo,
    changeRoles,
    logout,
    resetToken,
    _refreshToken
    // updateQuserStatus
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
